<template>
  <el-form ref="form" :model="form" :rules="rules">
    <el-form-item ref="phone" label="手机号" prop="phone">
      <el-input v-model.trim="form.phone" placeholder="请输入手机号" autofocus />
    </el-form-item>
    <el-form-item ref="code" label="验证码" prop="code">
      <el-input v-model="form.code" placeholder="请输入验证码" @keyup.enter.native="onSubmit">
        <send-code-btn
          slot="suffix"
          :phone="form.phone"
          class="m-r-10"
          @checkPhone="verifyPhone"
        />
      </el-input>
    </el-form-item>
    <el-form-item class="no-b-margin nlh">
      <el-button class="full" type="primary" @click="onSubmit" :loading="loading">注册并绑定</el-button>
      <span class="f-mini info-deep">注册后可以在【个人中心-密码】中设置登录密码</span>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapActions } from 'vuex';
import SendCodeBtn from '@/components/shared/SendCodeBtn';
import { formatUser } from '@/components/users/format';

export default {
  name: 'new_user_form', // 注册新用户
  components: { SendCodeBtn },
  data() {
    return {
      form: {
        phone: '', // 手机号
        code: '', // 验证码
      },
      rules: {
        phone: [{ validator: this.$va.phone, trigger: 'none' }],
        code: [{ validator: this.$va.code, trigger: 'none' }],
      },
      loading: false, // 注册中
    };
  },
  methods: {
    ...mapActions({ setCurUser: 'setCurrentUser' }),
    // 提交表单
    onSubmit() {
      this.$refs.form.validate((valid, errs) => {
        if (valid) {
          this.loading = true;
          this.$api.oauth.create({
            phone: this.form.phone,
            code: this.form.code,
            openId: this.$route.query.open_id,
            type: this.$route.query.type,
          }).then((res) => {
            this.$message.success('登录成功');
            this.setCurUser(formatUser(res.data));
            const redirect = localStorage.getItem('otherSignIn');
            localStorage.removeItem('otherSignIn');
            this.$router.push(redirect || '/users/edit');
          }).catch(() => {})
            .then(() => { this.loading = false; });
        } else this.$refs[Object.keys(errs)[0]].$el.scrollIntoView({ block: 'center' });
      });
    },
    // 触发验证手机号
    verifyPhone() { this.$refs.form.validateField('phone'); },
  },
};
</script>

<style></style>
